package com.jiuyue.movehouse.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiuyue.movehouse.common.enums.OrderState;
import com.jiuyue.movehouse.common.exception.BadRequestException;
import com.jiuyue.movehouse.entity.*;
import com.jiuyue.movehouse.mapper.CarMapper;
import com.jiuyue.movehouse.mapper.OrderMapper;
import com.jiuyue.movehouse.service.CarTypeService;
import com.jiuyue.movehouse.service.ExtInfoService;
import com.jiuyue.movehouse.service.OrderService;
import com.jiuyue.movehouse.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yourFather
 * @since 2022-02-11
 */
@Service
@AllArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private CarTypeService carTypeService;

    private ExtInfoService extInfoService;

    private UserService userService;

    private CarMapper carMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order reservation(Order order) {
        CarType carType = carTypeService.getById(order.getCarTypeId());
        order.setCarTypeName(carType.getName());
        StringBuffer extInfo = new StringBuffer("");
        List<ExtInfo> extInfoList = order.getExtInfoIds().size()!=0?extInfoService.listByIds(order.getExtInfoIds()):new ArrayList<>();
        for (ExtInfo info : extInfoList) {
            extInfo.append(info.getName()+ "、");
        }
        if (extInfo.length() > 1) {
            extInfo.deleteCharAt(extInfo.length() - 1);
        }
        order.setExtInfo(extInfo.toString());
        order.setState(1);
        order.setUsername(userService.getById(order.getUserId()).getUsername());
        this.save(order);
        userService.update(Wrappers.<User>lambdaUpdate().eq(User::getId,order.getUserId()).set(User::getHaveOrder,1));
        order.setStateName(OrderState.getById(order.getState()).getName());
        return order;
    }

    @Override
    public List<Order> getMyOrder(Long userId) {
        List<Order> orderList= this.list(Wrappers.<Order>lambdaQuery().eq(Order::getUserId,userId).orderByDesc(Order::getId));
        orderList.forEach(order -> order.setStateName(OrderState.getById(order.getState()).getName()));
        return orderList;
    }

    @Override
    public Order cancelOrder(Long orderId) {
        Order order = this.getById(orderId);
        if (order.getState().equals(1)){
            order.setState(2);
            this.updateById(order);
        }else {
            throw new BadRequestException("商家已接单,不能取消");
        }
        order.setStateName(OrderState.getById(order.getState()).getName());
        return order;
    }

    @Override
    public Order payOrder(Long orderId) {
        Order order = this.getById(orderId);
        if (order.getState().equals(4)){
            order.setPayTime(new Date());
            order.setState(5);
            this.updateById(order);
        }else {
            throw new BadRequestException("非配送完成状态,支付失败");
        }
        order.setStateName(OrderState.getById(order.getState()).getName());
        return order;
    }

    @Override
    public Page<Order> getOrderList(Page page, Order order) {
        Page<Order> orderPage = this.page(page,Wrappers.<Order>lambdaQuery()
                .like(StrUtil.isNotEmpty(order.getUsername()),Order::getUsername,order.getUsername())
                .like(StrUtil.isNotEmpty(order.getCarNumber()),Order::getCarNumber,order.getCarNumber())
                .eq(!Objects.isNull(order.getState()),Order::getState,order.getState()).orderByDesc(Order::getId));
        orderPage.getRecords().forEach(o ->{
            o.setStateName(OrderState.getById(o.getState()).getName());
            o.setPhone(userService.getByUserId(o.getUserId()).getPhone());
        } );
        return orderPage;
    }

    @Override
    public List<Car> getCarList() {
        return carMapper.selectList(Wrappers.<Car>lambdaQuery().eq(Car::getState,0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receiveOrder(Long orderId, Long carId) {

        Car car  = carMapper.selectById(carId);
        if (car.getState().equals(1)){
            throw new BadRequestException(car.getCarNumber()+"正在送货中");
        }
        car.setState(1);
        carMapper.updateById(car);

        Order order = this.getById(orderId);

        if (order.getState().equals(1)){
            order.setState(3);
            order.setReceiveTime(new Date());
            order.setCarNumber(car.getCarNumber());
            this.updateById(order);
        }else {
            throw new BadRequestException("订单"+ OrderState.getById(order.getState()).getName()+"状态,不能进行接单");
        }

    }

    @Override
    public void completeOrder(Long orderId, BigDecimal realPrice) {
        Order order = this.getById(orderId);

        if (order.getState().equals(3)){
            Car car  = carMapper.selectOne(Wrappers.<Car>lambdaQuery().eq(Car::getCarNumber,order.getCarNumber()));
            car.setState(0);
            carMapper.updateById(car);
            order.setState(4);
            order.setRealPrice(realPrice);
            order.setCompleteTime(new Date());
            this.updateById(order);
        }else {
            throw new BadRequestException("订单"+ OrderState.getById(order.getState()).getName()+"状态");
        }
    }
}
